<?php


namespace app\admin\controller;


use app\BaseController;
use think\App;

class Upload extends BaseController
{
    protected $uploadConfig=[];
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->uploadConfig=config('uploadConfig');
    }

    public function index(){

        $type=$this->request->post('fileType');
        if(empty($this->uploadConfig[$type]))
            api_return(50001,"上传类型-$type-不存在，请配置uploadConfig");
        $rule=[];
        if($this->uploadConfig[$type]['fileSize'])
            $rule[]='fileSize:'.$this->uploadConfig[$type]['fileSize'];
        if($this->uploadConfig[$type]['fileExt'])
            $rule[]='fileExt:'.$this->uploadConfig[$type]['fileExt'];
        $file = request()->file('file');
        if(!$file)
            api_return(50001,"请上传文件");
        try {
            validate(['file'=>implode('|',$rule)])->check(['file'=>$file]);
            $savename = \think\facade\Filesystem::putFile( 'temp', $file);
        } catch (\think\exception\ValidateException $e) {
            api_return(50001,$e->getMessage());
        }
        api_return(200,'',['tempPath'=>str_replace("\\",'/',$savename),'fileType'=>$type]);
    }
    public function previewTemp(){
        $temp=$this->request->get('tempPath');
        echo file_get_contents(app()->getRootPath() . 'runtime/storage/'.$temp);
    }
    public function download(){
        $fileName = $this->request->get('tempPath');
        $filePath = app()->getRootPath() . 'runtime/storage/' . $fileName;

        // 确保文件存在
        if (!file_exists($filePath)) {
            die("文件不存在");
        }

        // 设置HTTP头以触发下载
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));

        // 清除缓冲区并关闭输出缓冲
        flush();
        readfile($filePath);
        exit;
    }

}
